package com.zbw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbw.domain.Book;
import com.zbw.domain.BorrowingBooks;
import com.zbw.domain.Department;
import com.zbw.domain.User;
import com.zbw.domain.Vo.BorrowingBooksVo;
import com.zbw.mapper.BookMapper;
import com.zbw.mapper.BorrowingBooksMapper;
import com.zbw.mapper.DepartmentMapper;
import com.zbw.mapper.UserMapper;
import com.zbw.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private BorrowingBooksMapper borrowingBooksMapper;
    @Resource
    private BookMapper bookMapper;

    @Override
    public List<User> findUserByUserName(String userName) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("user_name",userName);
        List<User> users = userMapper.selectByMap(hashMap);
        return users;
    }

    @Override
    public List<Department> findAllDepts() {
        List<Department> list=departmentMapper.selectList(new QueryWrapper<>());
        List<Department> list2=departmentMapper.selectByMap(null);
        return list;
    }

    @Override
    public User userLogin(String userName, String password) {
        //LabmdaQuweyWrapper
        QueryWrapper<User> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.eq("user_name",userName).eq("user_pwd",password);
        List<User> users = userMapper.selectList(sectionQueryWrapper);
        //List<User> users = findUserByUserName(userName);
        
        if (users.size()==0) {
            return null;
        } else {
            return users.get(0);
        }
        
//        for (User user : users) {
//            if (user.getUserPwd().equals(password)) {
//                return user;
//            }
//        }
//        return null;
    }

    @Override
    public boolean updateUser(User user, HttpServletRequest request) {
        //获取session对象中user对象
        User sessionUser = (User) request.getSession().getAttribute("user");
        user.setUserId(sessionUser.getUserId());
        int res=userMapper.updateById(user);

        if (res > 0) {
            //修改成功，更新session对象
            User newUser = userMapper.selectById(user.getUserId());
            request.getSession().setAttribute("user", newUser);
            return true;
        }

        return false;
    }

    @Override
    public List<BorrowingBooksVo> findAllBorrowingBooks(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",user.getUserId());
        List<BorrowingBooks> borrowingBooksList=borrowingBooksMapper.selectByMap(map);
        if (null == borrowingBooksList) {
            return null;
        }
        //将数据库表对应的对象(Do)转化成视图层对象（VO）
        List<BorrowingBooksVo> res = new LinkedList<BorrowingBooksVo>();
        for (BorrowingBooks borrowingBooks : borrowingBooksList) {
            BorrowingBooksVo borrowingBooksVo = new BorrowingBooksVo();
            Book book = bookMapper.selectById(borrowingBooks.getBookId());
            borrowingBooksVo.setBook(book);

            //日期转换
            Date date1 = borrowingBooks.getDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateOfBorrowing = sdf.format(date1);

            //算出还书日期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            calendar.add(Calendar.MONTH, 2);//增加两个月
            Date date2 = calendar.getTime();
            String dateOfReturn = sdf.format(date2);

            borrowingBooksVo.setDateOfBorrowing(dateOfBorrowing);
            borrowingBooksVo.setDateOfReturn(dateOfReturn);
            res.add(borrowingBooksVo);
        }
        return res;
    }

    @Override
    public boolean userReturnBook(int bookId, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        HashMap<String, Object> map = new HashMap<>();
        map.put("bookId",bookId);
        int res= borrowingBooksMapper.deleteByMap(map);
        if (res > 0) return true;
        return false;
    }

    @Override
    public boolean userBorrowingBook(int bookId, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        //检查该书是否可借,从借书记录表中查询该书是否已借出
        HashMap<String, Object> map = new HashMap<>();
        map.put("bookId",bookId);
        List<BorrowingBooks> borrowingBooksList = borrowingBooksMapper.selectByMap(map);
        if (borrowingBooksList.size() > 0) {
            return false;
        }

        BorrowingBooks borrowingBooks = new BorrowingBooks();
        borrowingBooks.setBookId(bookId);
        borrowingBooks.setUserId(user.getUserId());
        borrowingBooks.setDate(new Date());
        int n = 0;
        try {
            //数据库中增加一条借书记录 【如果插入失败 , 则借书失败】
            n = borrowingBooksMapper.insert(borrowingBooks);
        } catch (Exception e) {
            // e.printStackTrace();
            return false;
        }


        if (n > 0) {
            return true;
        }
        return false;
    }

    @Override
    public User findUserById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public  Page<User> findUserByPage(int pageNum) {
        Page<User> page = new Page<>(pageNum, 5);
        userMapper.selectPage(page,null);

//        page.setList(users);
//        page.setPageNum(pageNum);
//        page.setPageSize(10);

//        int userCount = userMapper.selectCount();
//        int pageCount = userCount / 10;
//        if (userCount % 10 != 0) {
//            pageCount++;
//        }
       // page.setPageCount(pageCount);
        return page;
    }

    @Override
    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int deleteUserById(int userId) {
        return userMapper.deleteById(userId);
    }
}
